import Comment, { type CommentAttributes, type CommentCreationAttributes } from '../models/Comment'
import Post from '../models/Post'
import User from '../models/User'
import { Op } from 'sequelize'

export class CommentService {
  // 创建评论
  static async createComment(data: CommentCreationAttributes): Promise<Comment> {
    const comment = await Comment.create(data)
    
    // 更新帖子的评论数量
    await Post.increment('replyCount', {
      where: { id: data.postId }
    })
    
    return comment
  }

  // 获取帖子的评论列表（只获取顶级评论，不包含回复）
  static async getCommentsByPostId(
    postId: number,
    page: number = 1,
    pageSize: number = 10
  ): Promise<{ comments: Comment[]; total: number }> {
    const offset = (page - 1) * pageSize
    
    const { count, rows } = await Comment.findAndCountAll({
      where: { 
        postId,
        parentId: null // 只获取顶级评论
      } as any,
      include: [
        {
          model: User,
          as: 'author',
          attributes: ['id', 'username', 'name']
        },
        {
          model: Comment,
          as: 'replies',
          include: [
            {
              model: User,
              as: 'author',
              attributes: ['id', 'username', 'name']
            }
          ],
          order: [['createdAt', 'ASC']]
        }
      ],
      order: [['createdAt', 'ASC']],
      limit: pageSize,
      offset
    })

    return {
      comments: rows,
      total: count
    }
  }

  // 获取评论的回复列表
  static async getRepliesByCommentId(
    commentId: number,
    page: number = 1,
    pageSize: number = 10
  ): Promise<{ replies: Comment[]; total: number }> {
    const offset = (page - 1) * pageSize
    
    const { count, rows } = await Comment.findAndCountAll({
      where: { parentId: commentId },
      include: [
        {
          model: User,
          as: 'author',
          attributes: ['id', 'username', 'name']
        }
      ],
      order: [['createdAt', 'ASC']],
      limit: pageSize,
      offset
    })

    return {
      replies: rows,
      total: count
    }
  }

  // 根据ID获取评论
  static async getCommentById(id: number): Promise<Comment | null> {
    return await Comment.findByPk(id, {
      include: [
        {
          model: User,
          as: 'author',
          attributes: ['id', 'username', 'name']
        },
        {
          model: Post,
          as: 'post',
          attributes: ['id', 'title']
        }
      ]
    })
  }

  // 更新评论
  static async updateComment(id: number, data: Partial<CommentAttributes>): Promise<Comment | null> {
    const comment = await Comment.findByPk(id)
    if (!comment) {
      return null
    }

    await comment.update(data)
    return comment
  }

  // 删除评论
  static async deleteComment(id: number): Promise<boolean> {
    const comment = await Comment.findByPk(id)
    if (!comment) {
      return false
    }

    // 更新帖子的评论数量
    await Post.decrement('replyCount', {
      where: { id: comment.postId }
    })

    await comment.destroy()
    return true
  }

  // 获取用户的评论列表
  static async getCommentsByUserId(
    userId: number,
    page: number = 1,
    pageSize: number = 10
  ): Promise<{ comments: Comment[]; total: number }> {
    const offset = (page - 1) * pageSize
    
    const { count, rows } = await Comment.findAndCountAll({
      where: { authorId: userId },
      include: [
        {
          model: Post,
          as: 'post',
          attributes: ['id', 'title']
        }
      ],
      order: [['createdAt', 'DESC']],
      limit: pageSize,
      offset
    })

    return {
      comments: rows,
      total: count
    }
  }
}

export default CommentService
